import { showNotify,showConfirmDialog,showToast } from "vant";
import { useCookies } from "vue3-cookies";
import Request from "../services/request";
import business from "@/routers/business";

const { cookies } = useCookies(); //实例cookies方法,便于login()的调用

const NotifyWarn = (option) => {
  let msg = "未知信息";
  let duration = 1500;
  let fn = () => {};
  if (typeof option === "object") {
    msg = option.msg ?? msg;
    duration = option.duration ?? duration;
    fn = typeof option.onClose === "function" ? option.onClose : fn;
  } else if (typeof option === "string") {
    msg = option ?? msg;
  }
  //消息提醒
  showNotify({
    message: msg, //提示信息
    type: "warning", //提示消息的类型，警告类型
    duration: duration,
    onClose: fn,
  });
};

const NotifySuccess = (option) => {
  let msg = "未知信息";
  let duration = 1500;
  let fn = () => {};
  if (typeof option === "object") {
    msg = option.msg ?? msg;
    duration = option.duration ?? duration;
    fn = typeof option.onClose === "function" ? option.onClose : fn;
  } else if (typeof option === "string") {
    msg = option ?? msg;
  }
  //消息提醒
  showNotify({
    message: msg, //提示信息
    type: "success", //提示消息的类型，警告类型
    duration: duration,
    onClose: fn,
  });
};

// const login = async () => {
//   let business = Cookies.get("business") ? Cookies.get("business") : {};

//   if (!business || business.hasOwnProperty("id") === false) {
//     router.push("/business/base/login");
//     return { code: 0, msg: "请登录", data: null };
//   }
//   let id = business.id ?? 0;
//   let mobile = business.mobile ?? "";

//   let result = await Request.POST({
//     url: "business/base/check",
//     params: {
//       id,
//       mobile,
//     },
//   });

//   return result;
// };

//可以是公开 install() 方法的 object，也可以是 function,这里是公开函数
const install = (app) => {
  const login = async () => {
    let business = cookies.get("business") ? cookies.get("business") : {};

    if (!business || business.hasOwnProperty("id") === false) {
      return { code: 0, msg: "请登录", data: null };
    }

    let id = business.id ?? 0;
    let mobile = business.mobile ?? "";

    let result = await Request.POST({
      url: "business/base/check",
      params: {
        id,
        mobile,
      },
    });

    if (result.code === 1) {
      cookies.set('business',result.data);
      app.config.globalProperties.$business = ref(cookies.get('business')) ?? {};
    }

    return result;
  };
  //全局挂载
  app.config.globalProperties.$NotifyWarn = NotifyWarn;
  app.config.globalProperties.$NotifySuccess = NotifySuccess;
  app.config.globalProperties.$login = login;
  app.config.globalProperties.$showConfirm = showConfirmDialog;
  app.config.globalProperties.$business = ref(cookies.get('business')) ?? {};
  app.config.globalProperties.$showToast = showToast;
};

export default {
  install,
  NotifyWarn,
  NotifySuccess,
};
